import React, { PropTypes, Component } from 'react'
import fetch from 'isomorphic-fetch'
import { Link } from 'react-router'

import Table from './Table'
import NavLink from './NavLink'
import style from './addStore.css'

import { myAjax, ROOTURL, ROOTURL_MALL } from '../publicAPI/publicAPI'
import {tmToFormatTime} from './../publicAPI/commonF'

class MallOrderM extends Component {
    constructor (props, context) {
        super(props, context)
        console.log("初始化");

        this.state = {
            page: 1,
            delete: false,
            deleteId: -1,
            OrderData:[],
        } ;// 初始化状态


        this.start = 0; //从第几条获取订单
        this.limit = 10; //每页显示订单数目
        this.requestAll = false; //判断是否请求所有数据


        this.getOrders();



    }

    // 商品对应的中文名
    getNameCN(type, name){
      let arr = [];
      let str = "";
      switch (type) {
        case 'bolisuan':
          str += "玻尿酸：";
          if(name == "bolisuan-a"){
            str += "福瑞达玻尿酸";
          }else if(name == "bolisuan-b"){
            str += "其他品牌玻尿酸";
          }
          return str;
          break;
        case 'fangfuji':
          str += "防腐剂：";
          if(name == "fangfuji-a"){
            str += "防腐剂";
          }
          return str;
          break;
        case 'meibai':
          str += "美白：";
          if(name == "meibai-a"){
            str += "美白（传明酸）";
          }
          return str;
          break;
        case 'meiguijingyou':
          str += "玫瑰精油（润肤）：";
          if(name == "meiguijingyou-a"){
            str += "玫瑰精油（润肤）"
          }
          return str;
          break;
        case 'mobu':
          str += "膜布：";
          if(name == "mobu-a"){
            str += "进口蚕丝膜布（双层）";
          }else if(name == "mobu-b"){
            str += "植物纤维天丝膜布（双层）";
          }else if(name == "mobu-c"){
            str += "竹炭纤维黑膜布（单层）";
          }
          return str;
          break;
        case 'shuliang':
          str += "数量：";
          if(name == "shuliang-a"){
            str += "6片/盒";
          }else if(name == "shuliang-b"){
            str += "12片/盒";
          }
          return str;
          break;
        case 'xiangjing':
          str += "香精：";
          if(name == "xiangjing-a"){
            str += "花香（复合型香味）";
          }else if(name == "xiangjing-b"){
            str += "果香（复合型香味）";
          }else if(name == "xiangjing-c"){
            str += "木香（复合型香味）";
          }
          return str;
          break;
        case 'xunyicaojingyou':
          str += "薰衣草精油：";
          if(name == "xuanyicaojingyou-a"){
            str += "薰衣草精油（舒缓宁神）";
          }
          return str;
          break;
        case 'zirun':
          str += "滋润：";
          if(name == "zirun-a"){
            str += "霍霍芭油";
          }else if(name == "zirun-b"){
            str += "玫瑰果油";
          }
          return str;
          break;
        case 'zhiwu1':
          str += "芦荟或白芨：";
          if(name == "baiji"){
            str += "白芨";
          } else if( name == "luhui") {
            str += "芦荟";
          }
          return str;
          break;
        case 'zhiwu2':
          str += "木瓜或黄瓜：";
          if(name == "mugua"){
            str += "木瓜";
          } else if( name == "huanggua") {
            str += "黄瓜";
          }
          return str;
          break;
        case 'zhiwu3':
          str += "绿茶或石榴：";
          if(name == "shiliu"){
            str += "石榴";
          } else if( name == "lvcha") {
            str += "绿茶";
          }
          return str;
          break;
        default:
          break;
      }
    }

    getOrders(){
        var URL = ROOTURL_MALL +'kabuy/contract/search.api';
        var _this = this ;
        var data2 = [];
        var customerArr = [];
        fetch(URL, {
            method : 'POST',
            mode: "cors",
            body: JSON.stringify({
                "where":{
                   dd: [
                        ["eq",false]
                    ],
                  },
                  "order":[
                    ["tmCreate", "desc"]
                  ],
                  start: _this.start,
                  limit: _this.limit
            })
        })
        .then(res => {
          return new Promise((resolve, reject) => {
            if(res.ok){
                res.json().then(data => {
                    if(data.length < self.limit) {
                        self.requestAll = true
                    } else {
                        self.requestAll = false
                    }

                    for(var k=0; k<data.length; k++){
                        if(data[k].kaStatus==0){
                            data[k].kaStatus="未支付";
                        }else if(data[k].kaStatus==(-128)){
                            data[k].kaStatus="超时未支付";
                        }else if(data[k].kaStatus==(-96)){
                            data[k].kaStatus="未及时到店取货";
                        }else if(data[k].kaStatus==(-64)){
                            data[k].kaStatus="支付异常";
                        }else if(data[k].kaStatus==(16)){
                            data[k].kaStatus="已支付";
                        }else if(data[k].kaStatus==(-80)){
                            data[k].kaStatus="申请退款";
                        }else if(data[k].kaStatus==(-79)){
                            data[k].kaStatus="已核准退款";
                        }else if(data[k].kaStatus==(-78)){
                            data[k].kaStatus="已拒绝退款";
                        }

                        if(data[k].isPick==true){
                            data[k].kaStatus="已取货";
                        }

                        let innerArr = [];
                        if(data[k].meta && data[k].meta.ItemOption){
                          let _ItemOption = data[k].meta.ItemOption;
                          for(let item in _ItemOption){
                            if(_ItemOption[item] !== ""){
                              let tmp =
                              innerArr.push(_this.getNameCN(item, _ItemOption[item]));
                            }
                          }
                        }

                        data[k].inner = innerArr;

                        data[k].shopName = data[k].meta.shopname;
                        // data[k].wechatname = data[k].meta.wechatname;
                        // data[k].wechatphone = data[k].meta.wechatphone;
                        customerArr.push(data[k].customerId)
                        data2.push(data[k]);

                    }
                    _this.setState({
                       OrderData:data2
                    })
                    resolve();
                })
            }
          })

        })
        .then((res) => {

          // 找到收货人和地址
          var URL1 = ROOTURL_MALL + 'kabuy/shipaddress/search.api';

          fetch(URL1, {
              method : 'POST',
              mode: 'cors',
              body: JSON.stringify({
                        "where":{
                          "customerId":[
                            ["in", customerArr]
                          ]
                        },
                        "start":0,
                   })
          }).then(res=>{
              if(res.ok){
                  res.json().then(param1=>{

                      for(var count_1 = 0 ; count_1 < data2.length; count_1 ++){
                          for(var count_1_man = 0 ; count_1_man < param1.length ; count_1_man ++ ){
                              if( data2[count_1].customerId == param1[count_1_man].customerId ){
                                  data2[count_1].shouMan = param1[count_1_man].cname;
                                  data2[count_1].shouAddr = param1[count_1_man].fullAddr;
                                  data2[count_1].phonecall = param1[count_1_man].cphone;
                              }
                          }
                      }
                      _this.setState({
                         OrderData:data2
                      })
                  })
              }
          })

          //找到顾客信息
          var URL2 = ROOTURL + 'customer/info/search.api';

          fetch(URL2, {
              method : 'POST',
              mode: 'cors',
              body: JSON.stringify({
                        "where":{
                          "customerId":[
                            ["in", customerArr]
                          ]
                        }
                   })
          }).then(res=>{
              if(res.ok){
                  res.json().then(param2=>{
                      for(var count_1 = 0 ; count_1 < data2.length; count_1 ++){
                          for(var count_1_man = 0 ; count_1_man < param2.length ; count_1_man ++ ){
                              if( (data2[count_1].customerId == param2[count_1_man].customerId) && param2[count_1_man].skin!=undefined){
                                  data2[count_1].skin = param2[count_1_man].skin;
                              }
                          }
                      }
                      _this.setState({
                         OrderData:data2
                      })
                  })
              }
          })



          //找到商品资料
          var URL3 = ROOTURL_MALL +'kabuy/item/search.api';

          fetch(URL3, {
              method : 'POST',
              mode: 'cors',
              body: JSON.stringify({

                   })
          }).then(res=>{
              if(res.ok){
                  res.json().then(param3=>{
                      for(var count_1 = 0 ; count_1 < data2.length; count_1 ++){
                          for(var count_1_item = 0 ; count_1_item < param3.length ; count_1_item ++ ){

                              if( data2[count_1].itemId == param3[count_1_item].id ){
                                  data2[count_1].productName = param3[count_1_item].name;
                                  if(param3[count_1_item].meta){
                                    data2[count_1].typeName = param3[count_1_item].meta.typeName;
                                  }

                              }
                          }
                      }
                      _this.setState({
                         OrderData:data2
                      })
                  })
              }
          })
        })

    }

    //翻页按钮
    handlePageClick(e) {//1为下一页，2为上一页
        const _buttonValue = e.target.value

        if(_buttonValue == 1) {
            this.start = this.start + this.limit -1

        } else {
            this.start = this.start - this.limit + 1
        }
        this.getOrders()
    }

    componentWillMount() {
         console.log("将安装");
    }

    componentDidMount() {
        console.log("安装成功");
    }

    tHead() {
        var data = [
            {name: "id"},
            {name: "订单创建时间"},
            {name: "客户手机号"},
            {name: "商品名"},
            {name: "种类名"},
            {name: "材料"},
            {name: "肤质"},
            {name: "购买数"},
            {name: "实付¥"},
            {name: "订单状态"},
            {name: "收货人"},
            {name: "收货地址"},
        ];
        const _headArr = [];
        const _width = {
            "0" : "3%",
            "1" : "8%",
            "2" : "8%",
            "3" : "7%",
            "4" : "7%",
            "5" : "22%",
            "6" : "5%",
            "7" : "7%",
            "8" : "7%",
            "9" : "7%",
            "10" : "7%",
            "11" : "10%",
        };
        //_headArr.push(<th style={{width:'5%'}} role="1" key='' onClick={(e) => this.handleSelect(e)}></th>)
        _headArr.push(data.map((item, index) => <th style={{width: _width[index]}} role="1" key={index}>{item.name}</th>))
        return _headArr;
    }

    tBody() {



        var _data = [


        ];
        return this.state.OrderData.map(item => <tr key={item.id}>
                    <td>{item.id}</td>
                    <td>{item.tmCreate ? tmToFormatTime(item.tmCreate) : ''}</td>
                    <td>{item.phonecall}</td>
                    <td>{item.productName}</td>
                    <td>{item.typeName ? item.typeName : ""}</td>

                    <td style={{textAlign: 'left'}}>
                    {
                      item.inner.map((item,index)=>{
                        return <span key={index}>{item}<br /></span>
                      })
                    }
                    </td>
                    <td>{item.skin}</td>
                    <td>{item.itemCounts}</td>
                    <td>{item.netPay}</td>
                    <td>{item.kaStatus}</td>
                    <td>{item.shouMan ? item.shouMan : ""}</td>
                    <td>{item.shouAddr ? item.shouAddr : ""}</td>
                </tr>)


    }

    render(){
        return (

            <div className="right-wapper ">
                <div className="rt-wrap">
                    <h2 className="catagory">
                        <Link to={`/MallIndex`}><span className={style['cata-title']}>首页轮播图</span></Link>
                        <Link to={`/MallProductTypeM`}><span className={style['cata-title']}>商品分类管理</span></Link>
                        <Link to={`/MallProductsM`}><span className={style['cata-title']}>商品管理</span></Link>
                        <Link to={`/MallOrderM`}><span className={style['cata-title-current']}>订单管理</span></Link>
                        <Link to={`/MallStoreM`}><span className={style['cata-title']}>门店管理</span></Link>
                        <Link to={`/MallMember`}><span className={style['cata-title']}>门店店员管理</span></Link>
                        <Link to={`/MallStatisticsM`}><span className={style['cata-title']}>商城统计</span></Link>
                        <Link to={`/MallCoupon`}><span className={style['cata-title']}>优惠券管理</span></Link>
                        <button className="next" value="1" style={{display: this.requestAll ? "none" : "block"}} onClick={(e) => this.handlePageClick(e)}></button>
                        <button className="prev" value="2" style={{display: this.start ? "block" : "none"}} onClick={(e) => this.handlePageClick(e)}></button>
                    </h2>
                          <div style={{margin:'20px 0 5px'}}>
                    </div>
                    <Table tHead={this.tHead.bind(this)()} tBody={this.tBody.bind(this)()} tableClass="default-table ivanwrakeTB"/>
                </div>
                { this.state.delete ?
                    <div id={style.msgDialog}>
                        <div className={style['msgDialog_div']}><h3 id={style['msgDialog_title']}>删除提示？</h3><p id={style['msgDialog_content']}>确认删除？</p>
                            <div className={style['msgDialog_button']}>
                                <button id={style['msgDialog_yes']} onClick={this.deleteOrder.bind(this)}>确定</button>
                                <button id={style['msgDialog_no']} onClick={()=>this.setState({delete: !this.state.delete})}>取消</button>
                            </div>
                        </div>
                    </div> : null}

            </div>
        )
    }
}


export default MallOrderM
